import {
  getSearchHot,
  getSearchSuggest,
  getSearchResult
} from "../../api/search"
import throttle from "../../utils/throttle"

const throttleGetSearchSuggest = throttle(getSearchSuggest)

// pages/search/search.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hots: [],
    searchValue: '',
    suggestSongs: [],
    songsResult: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onGetSearchHot()
  },
  // 获取关键词
  async onGetSearchHot() {
    const res = await getSearchHot()
    // console.log(res);
    this.setData({
      hots: res.result.hots
    })
  },

  // 输入框改变
  searchChange(e) {
    const searchValue = e.detail
    // 保存关键字
    this.setData({
      searchValue
    })
    // 判断关键字，无，就清空上一次搜索建议
    if (!searchValue.length) {
      this.setData({
        suggestSongs: [],
        songsResult: []
      })
      return
    }
    // 获取搜索建议
    throttleGetSearchSuggest(searchValue).then(res => {
      if (!this.data.searchValue.length) {
        // console.log('取消了');
        return
      }
      // console.log(res);
      this.setData({
        suggestSongs: res.result.allMatch
      })
    })
  },

  // 获取搜索结果
  searchResult() {
    const searchValue = this.data.searchValue
    getSearchResult(searchValue).then(res => {
      // console.log(res);
      this.setData({
        songsResult: res.result.songs
      })
    })
  },

  // 点击关键词
  handleKeywordItemClick(e) {
    const keyword = e.currentTarget.dataset.keyword
    if (keyword) {
      this.setData({
        searchValue: keyword
      })
      this.searchResult()
    }
  },

  // 跳转到音乐详情页面
  onMusicDetail(e) {
    const id = e.target.dataset.id
    if(id) {
      wx.navigateTo({
        url: '/pages/music-player/music-player?id=' + id
      })
    }
  }
})